<template>
    <div>
        <div class="top">
            <div class="top-left" @click="toIndex">
                <img src="../assets/logo.png" width="200" height="65" alt="Logo">
            </div>
            <div class="top-right">
                <div class="collapse">
                    <i :class="isCollapse ? 'el-icon-s-fold' : 'el-icon-s-unfold'" @click="openCollapse"/>
                </div>
                <div class="top-right-right">
                    <el-dropdown size="mini" style="color: black">
                        <span class="head-content">
                            <img src="../assets/logo.png" class="head-image">
                                admin
                            <i class="el-icon-arrow-down"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item icon="el-icon-edit">
                                <span class="head-item" @click="updatePassword">修改密码</span>
                            </el-dropdown-item>
                            <el-dropdown-item icon="el-icon-switch-button">
                                <span class="head-item" @click="logout">退出</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="bottom-left" :class="{fold: isCollapse}">
                <el-menu class="left-aside"
                         :default-active="currentActiveMenu"
                         @select="menuSelect"
                         router
                         :style="{height:leftMenuHeight+'px'}"
                         background-color="#545c64"
                         text-color="#fff"
                         active-text-color="#ffd04b"
                         :collapse="isCollapse"
                         :collapse-transition="true"
                         unique-opened>
                    <template v-for="item in this.menuTree">
                        <el-submenu v-if="item.children" :index="item.id+'-'+item.url" :key="item.id">
                            <template slot="title">
                                <i :class="item.icon" style="color: white"/>
                                <span slot="title">{{item.name}}</span>
                            </template>
                            <vip-menu :menuTree="item.children"/>
                        </el-submenu>
                        <el-menu-item v-else :index="item.url" :key="item.id">
                            <i :class="item.icon" style="color: white"/>
                            <span>{{item.name}}</span>
                        </el-menu-item>
                    </template>
                </el-menu>
            </div>
            <div class="bottom-right">
                <div style="border-top: #f6f6f6 solid 1px"></div>
                <div style="overflow: hidden">
                    <div class="bottom-right-top" :style="{width: hMenuListWidth+'px'}">
                        <div class="menu" ref="leftButton">
                            <div><i class="el-icon-d-arrow-left"></i></div>
                        </div>
                        <div class="buttons" ref="buttons">
                            <div v-for="(menu,index) in hMenuList" :key="index" @click="toMenu(index)">
                                <div class="menu" :class="{'active':hCacheMenu.url===menu.url}">
                                    <div>{{menu.name}}</div>
                                    <i v-if="menu.url!==hCurrentActiveMenu" class="el-icon-close" @click.stop="closeMenu(index)"/>
                                </div>
                            </div>
                        </div>
                        <div style="position: fixed;right: 50px" class="menu" ref="rightButton">
                            <div><i class="el-icon-d-arrow-right"></i></div>
                        </div>
                        <div style="position: fixed;right: 0" ref="tabButton">
                            <el-dropdown size="mini" style="color: black">
                                <span>
                                    <div class="menu">
                                        <div><i class="el-icon-arrow-down"></i></div>
                                    </div>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item icon="">
                                        <span class="head-item" @click="closeCurrentTab">关闭当前标签</span>
                                    </el-dropdown-item>
                                    <el-dropdown-item icon="">
                                        <span class="head-item" @click="closeOtherTab">关闭其他标签</span>
                                    </el-dropdown-item>
                                    <el-dropdown-item icon="">
                                        <span class="head-item">关闭所有标签</span>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                          </div>
                    </div>
                </div>
                <div style="overflow-y: auto" :style="{height:leftMenuHeight-60+'px'}">
                    <keep-alive>
                        <router-view :userInfo="$store.state.userInfo" v-if="$route.meta.keepAlive"/>
                    </keep-alive>
                    <router-view :userInfo="$store.state.userInfo" v-if="!$route.meta.keepAlive"/>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { mapMutations } from 'vuex'
    import VipMenu from "@/components/menu/VipMenu";
    export default {
        name: "Home",
        components: {
            VipMenu
        },
        data(){
            return{
                isCollapse: false,//菜单：false:展开，true:折叠
                leftMenuHeight:0,
                menuTree:[],
                //当前激活的菜单
                currentActiveMenu:this.$store.state.currentActiveMenu||'',
                //暂存点击的菜单名字，也可作为当前激活的横向菜单
                hCurrentActiveMenu:'',
                hCacheMenu:{},
                hMenuList:[],
                webSocket:null,
                loginVisible:false,
                hMenuListWidth:10000
            }
        },
        created(){
            //获取屏幕高度给左侧列表
            this.leftMenuHeight = window.innerHeight-60;
            //窗口变动回调
            window.onresize = () =>{
                this.leftMenuHeight = window.innerHeight-60
            };
            //获取导航列表
            this.getMenus()
            //获取横向菜单列表
            this.getHMenuList()
            //初始化WebSocket
            // this.initWebSocket()
            // this.$nextTick(()=>{
            //     this.hMenuListWidth =
            //         this.hMenuListWidth = this.$refs.buttons.clientWidth+
            //             this.$refs.leftButton.clientWidth+
            //             this.$refs.rightButton.clientWidth+
            //             this.$refs.tabButton.clientWidth+267
            //         console.log(this.$refs.buttons.clientWidth)
            // })
        },
        methods:{
            ...mapMutations([`clearStore`, `setCurrentActiveMenu`]),
            //获取菜单列表
            getMenus(){
                let url = "menu/tree";
                this.$http.get(url).then(res => {
                    if(res.data.code===0){
                        this.menuTree = res.data.data.items
                        if(this.menuTree){
                            let firstMenu = this.menuTree[0]
                            this.initMenu(firstMenu)
                        }
                    }
                })
            },
            //初始化菜单
            initMenu(firstMenu){
                this.hCurrentActiveMenu = this.getHCurrentActiveMenu()
                if(!this.hCurrentActiveMenu){
                    this.hCurrentActiveMenu = firstMenu.url
                    this.hMenuList.push(firstMenu)
                    this.updateHCurrentActiveMenu()
                }else{
                    firstMenu.url = this.hCurrentActiveMenu
                    this.hMenuList.shift()
                    this.hMenuList.unshift(firstMenu)
                }
                if(this.currentActiveMenu){
                    this.hCacheMenu.url = this.currentActiveMenu
                }else{
                    this.hCacheMenu = firstMenu
                    this.currentActiveMenu = firstMenu.url
                }
                this.setCurrentActiveMenu(this.hCacheMenu.url)
            },
            //选择菜单
            menuSelect(index) {
                this.currentActiveMenu = index
                this.setCurrentActiveMenu(index)
                let splits = index.split('-');
                let last = splits[splits.length - 1];
                if (last.startsWith('/')) {
                    if (this.$route.path !== last) {
                        this.$router.push({path:last})
                    }
                }
                //向横向菜单中添加菜单
                let menuObj = {}
                menuObj.name = this.getTreeData(this.menuTree,last)
                menuObj.url = last
                this.addMenu(menuObj)
            },
            // 递归判断列表，把最后的children设为undefined
            getTreeData(data,url){
                for(let i=0;i<data.length;i++){
                    if(data[i].url===url){
                        this.hCacheMenu = data[i]
                        break
                    }
                    if(data[i].children){
                        // children若不为空数组，则继续 递归调用 本方法
                        this.getTreeData(data[i].children,url);
                    }else {
                        // children若为空数组，则将children设为undefined
                        data[i].children=undefined;
                    }
                }
                return this.hCacheMenu.name;
            },
            //伸缩左侧列表
            openCollapse(){
                this.isCollapse = !this.isCollapse
            },
            //回首页
            toIndex(){
                this.$router.push({path:this.hCurrentActiveMenu})
                this.setCurrentActiveMenu(this.hCurrentActiveMenu)
            },
            //更新密码
            updatePassword(){

            },
            //注销
            logout(){
                let url = '/logout'
                this.$http.post(url).then(res=>{
                  if(res.data.code===0){
                    this.clearStore()
                    this.$router.push('/login')
                    this.$message.success('退出成功')
                  }
                })
            },
            //添加横向菜单
            addMenu(menu){
                let trueMenu
                let flag = false
                for(let i=0;i<this.hMenuList.length;i++){
                    if(this.hMenuList[i].url===menu.url){
                        trueMenu = this.hMenuList[i]
                        flag = true
                        break
                    }
                }
                if(!flag){
                    menu.id = this.hMenuList.length
                    this.hMenuList.push(menu)
                    this.updateHMenuList()
                }else{
                    this.hCacheMenu = trueMenu
                }
            },
            //关闭横向菜单
            closeMenu(index){
                let currentMenu = this.hMenuList[index]
                let len = this.hMenuList.length-1
                let lastMenu = this.hMenuList[len]
                if(currentMenu.id===lastMenu.id){
                    let menu = this.hMenuList[len-1]
                    //移除横向菜单的第index个
                    this.hMenuList.splice(index,1)
                    let url = menu.url
                    this.currentActiveMenu = url
                    this.setCurrentActiveMenu(url)
                    this.$router.push(url)
                    this.hCacheMenu = menu
                }else{
                    //如果移除的菜单和暂存的菜单一致
                    if(currentMenu.id===this.hCacheMenu.id){
                        this.hMenuList.splice(index,1)
                        let menu = this.hMenuList[len-1]
                        let url = menu.url
                        this.currentActiveMenu = url
                        this.setCurrentActiveMenu(url)
                        this.$router.push(url)
                        this.hCacheMenu = menu
                    }else{
                        this.hMenuList.splice(index,1)
                    }
                }
                this.updateHMenuList()
            },
            //去这个横向菜单
            toMenu(index){
                this.hCacheMenu = this.hMenuList[index]
                console.log(this.hCacheMenu.url)
                this.currentActiveMenu = this.hCacheMenu.url
                this.setCurrentActiveMenu(this.hCacheMenu.url)
                this.$router.push(this.hCacheMenu.url)
            },
            //更新一下缓存的横向菜单
            updateHMenuList(){
                sessionStorage.removeItem('hMenuListKey')
                sessionStorage.setItem('hMenuListKey',JSON.stringify(this.hMenuList))
            },
            //获取缓存的横向菜单
            getHMenuList(){
                let hMenuList = sessionStorage.getItem('hMenuListKey')
                if(hMenuList){
                    this.hMenuList = JSON.parse(hMenuList)
                }
            },
            //更新缓存的第一个横向菜单
            updateHCurrentActiveMenu(){
                sessionStorage.removeItem('hCurrentActiveMenuKey')
                sessionStorage.setItem('hCurrentActiveMenuKey',this.hCurrentActiveMenu)
            },
            //获取缓存的第一个横向菜单
            getHCurrentActiveMenu(){
                return sessionStorage.getItem('hCurrentActiveMenuKey')
            },
            //关闭当前选中标签
            closeCurrentTab(){
                this.hCacheMenu = this.getMenuByUrl(this.hCacheMenu.url)
                this.closeMenu(this.hCacheMenu.id)
            },
            //关闭其他标签
            closeOtherTab(){
                //TODO 关闭其他标签
                // for(let i in this.hMenuList){
                //     if(this.hMenuList[i].url!==this.hCacheMenu.url){
                //         let hMenu = this.hMenuList[i]
                //         if(hMenu.url!=='/index'){
                //             console.log(hMenu)
                //             this.closeMenu(hMenu.id)
                //         }
                //     }
                // }
            },
            closeAllTab(){
                //TODO 关闭所有标签
            },
            getMenuByUrl(url){
                for(let i in this.hMenuList){
                    if(this.hMenuList[i].url===url){
                        return this.hMenuList[i]
                    }
                }
            },
            //初始化WebSocket
            initWebSocket(){
                let userId = this.$store.state.userId
                let url = this.$store.state.ws+'websocket/'+userId;
                if(null===this.webSocket){
                    this.webSocket = new WebSocket(url)
                    this.webSocket.onopen = this.onOpen
                    this.webSocket.onmessage = this.onMessage
                    this.webSocket.onerror = this.onError
                    this.webSocket.onclose = this.onClose
                }
            },
            onOpen(){
                console.log('连接成功')
            },
            onMessage(e){
                //在这里接收推送的数据，进行处理
                console.log(e.data)
            },
            onError(){
                console.log('连接错误')
                //todo 可以重连
            },
            onClose(){
                console.log('关闭连接')
                this.webSocket.close()
            }
        }
    }
</script>

<style scoped>
    .content{
        margin: 10px;
        padding: 10px;
        background-color: white;
        box-shadow: 4px 4px 10px #e6e6e6;
        overflow: auto;
    }
    .left-aside:not(.el-menu--collapse){
        width: 200px;
    }
    .top{
        display: flex;
        align-items: center;
        height: 59px;
    }
    .top-left{
        width: 200px;
        cursor: pointer;
    }
    .top-right{
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
        background-color: white;
        height: 100%;
    }
    .collapse{
        margin-left: 20px;
        font-size: 25px;
        color: black;
    }
    .collapse:hover{
        color: black;
        cursor: pointer;
    }
    .top-right-right{
        margin-right: 50px;
        cursor: pointer;
    }
    .bottom{
        display: table;
        table-layout: fixed;
        width: 100%;
    }
    .bottom-left{
        width: 200px;
        display: table-cell;
        position: relative;
        /* 动画（宽度从200过度到65） */
        transition: width 0.3s linear;
        -moz-transition: width 0.3s linear; /* Firefox 4 */
        -webkit-transition: width 0.3s linear; /* Safari 和 Chrome */
        -o-transition: width 0.3s linear; /* Opera */
    }
    /* 收缩 */
    .fold{
        width: 65px;
        /* 动画（宽度从65过度到200） */
        transition: width 0.3s;
        -moz-transition: width 0.3s linear; /* Firefox 4 */
        -webkit-transition: width 0.3s linear; /* Safari 和 Chrome */
        -o-transition: width 0.3s linear; /* Opera */
    }
    .bottom-right{
        display: flex;
        flex-direction: column;
        background-color: #f0f0f0;
    }
    .bottom-right-top{
        display: flex;
        align-items: center;
        height: 40px;
        background-color: white;
    }
    .buttons{
        display: flex;
    }
    /* 菜单 */
    .menu{
        display: flex;
        justify-content: center;
        align-items: center;
        padding-left: 17px;
        padding-right: 17px;
        height: 40px;
        border-left: #f6f6f6 solid 1px;
        border-right: #f6f6f6 solid 1px;
        margin:0 -1px -1px 0;
        font-size: 15px;
        background-color: white;
    }
    /* 菜单按下 */
    .active{
        background-color: #66B1FF;
        color: white;
    }
    /* 鼠标移上菜单 */
    .menu:hover{
        cursor: pointer;
        background-color: #66B1FF;
        color: white;
    }
    .el-icon-close{
        margin-left: 5px;
    }
    .el-icon-close:hover{
        background-color: #e6e6e6;
        border-radius: 10px;
    }
    /* 头部内容 */
    .head-content{
        font-size: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 120px
    }
    /* 头像 */
    .head-image{
        width: 40px;
        height: 40px;
        border-radius: 50px;
        background-color: #F0F0F0;
    }
    /* 头像下拉菜单 */
    .head-item{
        display: inline-block;
        width: 80px;
        margin-top: 5px;
        margin-bottom: 5px
    }
</style>
